﻿using System;
using ReAnimation.Domain.Policies.Interfaces;
using ReAnimation.MVP.Models.Interfaces;
using ReAnimation.MVP.Presenters.Helpers;
using ReAnimation.MVP.ViewInterfaces;
using ReAnimation.Infrastructure.Services.Interfaces;

namespace ReAnimation.MVP.Presenters
{
    public class ZMatrixTablePresenter: BasePresenter<IZMatrixTable>
    {
        private readonly IMainModel _mainModel;
        private readonly IZMatrixPolicy _zMatrixPolicy;
        private readonly IZMatrixService _zMatrixService;

        public ZMatrixTablePresenter(IMainModel mainModel,
                                     IZMatrixPolicy zMatrixPolicy,
                                     IZMatrixService zMatrixService)
        {
            _zMatrixPolicy = zMatrixPolicy;
            _zMatrixService = zMatrixService;
            _mainModel = mainModel;
            _mainModel.CurrentMoleculeChanged += MainModelOnCurrentMoleculeZMatrixChanged;
            _mainModel.CurrentMoleculeZMatrixChanged += MainModelOnCurrentMoleculeZMatrixChanged;
        }

        private void MainModelOnCurrentMoleculeZMatrixChanged(object sender, EventArgs eventArgs)
        {
            using (BatchLayoutChange.For(_view))
            {
                if (_mainModel.CurrentMolecule != null)
                {
                    _view.ZMatrix = _mainModel.CurrentMolecule.MoleculeZMatrix;
                    if(_zMatrixService.ConvertZMatrixToCartesian(_mainModel.CurrentMolecule.MoleculeZMatrix,_mainModel.CurrentMolecule))
                        _mainModel.CurrentMoleculeStructureWasModified();
                }
                else
                    _view.ZMatrix = null;
                DisplayZMatrixValidationResult();
            }
        }

        private void DisplayZMatrixValidationResult()
        {
            if(_mainModel.CurrentMolecule != null)
            _view.ErrorState = !_zMatrixPolicy.CheckZMatrix(_mainModel.CurrentMolecule.MoleculeZMatrix);
            else
            {
                _view.ErrorState = true;
            }

           
        }

        protected override void InitView()
        {
            _view.ZMatrixChanged += ViewOnZMatrixChanged;
        }

        private void ViewOnZMatrixChanged(object sender, EventArgs eventArgs)
        {
            DisplayZMatrixValidationResult();
            MainModelOnCurrentMoleculeZMatrixChanged(null, EventArgs.Empty);
        }
    }
}
